//Encontrado no video Java Básico - 19 - Busca Avançada
// do canal newprogrammingway
// Autor do código é desconhecido.

import java.sql.*;
import java.util.*;

import javax.swing.*;
import javax.swing.table.*;
//import javax.swing.table.AbstractTableModel;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;


public class ResultSetTableModel extends AbstractTableModel {


      private static class Column {
          
	public final Class<?> CLASS;
	
	public final String  NAME;

        public Column(final String name, final Class<?> type){

            NAME = name;
            CLASS = type;
       }
    }
    
    private static class Row {
       
         public final Object[] VALUES;

         public Row(final ResultSet rs) throws SQLException {
         final int columns = rs.getMetaData().getColumnCount();
         VALUES = new Object[columns];
         for(int i = 1; i<=columns; i++){
             VALUES[i - 1] = rs.getObject(i);
        }
     }
  }

  private List<Column>     columns;
  private List<Row>        lines;
  
  public ResultSetTableModel(final ResultSet rs) throws SQLException,           
                                                    ClassNotFoundException {

  columns = new ArrayList<Column>(); 
  final ResultSetMetaData md = rs.getMetaData();
  final int count = md.getColumnCount();
  for(int i = 1; i <= count; i++){
      columns.add(new Column(md.getColumnName(i),
                              Class.forName(md.getColumnClassName(i))));
  }
  lines = new ArrayList<Row>();
   while(rs.next()){
        lines.add(new Row(rs));
    }
  }

 @Override
  public Class<?> getColumnClass(final int columnIndex){
         return columns.get(columnIndex).CLASS;
 }
  @Override
  public int getColumnCount(){
         return columns.size();
 }
  @Override
  public String getColumnName(final int column){
         return columns.get(column).NAME;
 }
    @Override
  public int getRowCount(){
         return lines.size();
 }
    @Override 
  public Object getValueAt(final int rowIndex, final int columnIndex){
         return lines.get(rowIndex).VALUES[columnIndex];
 }
    @Override
  public boolean isCellEditable(final int rowIndex, final int columnIndex) {
         return false;
 }
}